<!--
	作者：offline
	时间：2018-12-08
	描述：物料防伪
-->
<template>
  <div class="m-view-companyInfo m-window">
    <div class="m-condition">
      <el-row :gutter="10">
        <el-form
          :model="haderRuleForm"
          ref="haderRuleForm"
          label-width="100px"
          :inline-message="true"
          label-position="left"
        >
          <el-col :span="6">
            <el-form-item label="物料编号" class="rightItem">
              <el-input
                v-model="matCode"
                placeholder="请输入物料编号"
                clearable
                @keyup.enter.native="search"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料描述" class="rightItem">
              <el-input
                v-model="matName"
                placeholder="请输入物料描述"
                clearable
                @keyup.enter.native="search"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-form>
        <el-col :span="2" :offset="4">
          <el-button type="primary" @click="search">查询</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="add">新增</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="del">删除</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="importInfo">导入</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="m-agTable m-bottom">
      <agGridComponents
        ref="agGridComponent"
        :getGridOptions="gridOptions"
        :getColumnDefs="columnDefs"
        :isColFit="true"
      ></agGridComponents>
    </div>
    <div class="m-page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @prev-click="handlePrevClick"
        @next-click="handleNextClick"
        :current-page="currentPage"
        :page-sizes="[30, 50, 100, 150, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-dialog
      title="新增"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-form-item label="物料编号" prop="matCode">
          <el-input
            v-model="ruleForm.matCode"
            placeholder="请输入10位物料编号"
            clearable
            maxlength="10"
            @keyup.native="check"
            @blur="matCodeBlur"
            @keyup.enter.native="matCodeBlur"
            :disabled="inputDis"
          ></el-input>
        </el-form-item>
        <el-form-item label="物料描述" prop="matCode">
          <el-input
            v-model="ruleForm.matName"
            placeholder="物料描述"
            disabled
            clearable
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="isBarCode">
          <el-checkbox
            v-model="ruleForm.isBarCode"
            label="扫码出库"
          ></el-checkbox>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveData" :disabled.sync="disState"
          >保存</el-button
        >
        <el-button
          type="primary"
          @click="saveDataAgain"
          :disabled.sync="disState"
          >保存并继续</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="导入模板"
      v-if="importDialogVisible"
      :visible.sync="importDialogVisible"
      width="50%"
      :before-close="importHandleClose"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <importFile
        :moduleName="moduleName"
        @setImportData="getImportData"
        :closeImportDialog="importDialogVisible"
        :tempUrl="tempUrl"
      ></importFile>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveImportData">导入</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import agGridComponents from "@/components/agGridComponents";
import importFile from "@/components/importFile";
import fileStream from "@/public/fileStream";

export default {
  data() {
    return {
      matCode: "",
      matName: "",
      currentPage: 1,
      pageSize: 30,
      total: 0,
      gridOptions: "",
      columnDefs: "",
      dialogVisible: false,
      ruleForm: {
        isBarCode: "",
        matCode: "",
        matName: "",
      },
      haderRuleForm: {},
      rules: {
        matCode: [
          {
            required: true,
            message: "请输入10位物料编号",
          },
          {
            min: 10,
            max: 10,
            trigger: "change",
            message: "请输入10位物料编号",
          },
        ],
        matName: [
          {
            required: true,
            message: "请输入正确的物料编号再获取物料描述！",
          },
        ],
      },
      disState: false,
      rowData: [],
      current: 1,
      inputDis: false,
      importDialogVisible: false,
      moduleName: "materialAntiCounterfeition",
      importData: "",
      closeImportDialog: false,
      //   物料导入模板下载地址
      tempUrl: "",
    };
  },
  beforeMount() {
    this.gridOptions = {
      context: {
        componentParent: this,
      },
      rowSelection: "multiple",
      enableColResize: true,
      localeText: localeText,
      // getContextMenuItems:[],
      defaultColDef: {
        menuTabs: [],
      },
      suppressRowClickSelection: true, //单元格选中,false为选中整行
    };
    this.columnDefs = [
      {
        headerName: "物料编号",
        field: "matCode",
        checkboxSelection: true,
        width: 140,
      },
      {
        headerName: "物料描述",
        field: "matName",
        width: 260,
        tooltipField: "matName",
      },
      {
        headerName: "扫码出库",
        field: "isBarCode",
        editable: false,
        width: 90,
        cellRenderer: function (params) {
          if (params.value === 1)
            return '<span class="ag-icon ag-icon-checkbox-checked" ></span>';
          else
            return '<span class="ag-icon ag-icon-checkbox-unchecked" ></span>';
        },
      },
    ];
  },
  methods: {
    importHandleClose(done) {
      done();
      this.importDialogVisible = false;
    },
    saveImportData() {
      if (!this.importData) {
        this.$alert("提示：请导入相关数据！", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      }
      var that = this;
      for (var i in this.importData) {
        this.importData[i].creator = this.$global.user.employeeName;
        this.importData[i].creatorId = this.$global.user.id;
      }
      _Api
        .saveBatchMaterial(this.importData)
        .then(function (response) {
          var data = response.data;
          that.importDialogVisible = false;
          if (data.code == "1") {
            that.$message({
              message: "操作成功",
              type: "success",
            });
          } else {
            that.$alert(data.info, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure",
            });
          }
        })
        .catch((err) => {
          that.$alert(err.data.message, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
        });
    },
    getImportData(params) {
      this.importData = params;
    },
    search() {
      var obj = {};
      var that = this;
      obj.likeParams = {};
      if (this.matCode != "") obj.likeParams.matCode = this.matCode;
      if (this.matName != "") obj.likeParams.matName = this.matName;
      if (this.matCode || this.matName) {
        this.currentPage = 1;
        this.pageSize = 30;
        obj.current = 1;
        obj.size = 30;
      } else {
        obj.current = this.currentPage;
        obj.size = this.pageSize;
      }
      //				obj.current = this.current;
      //				obj.size = this.pageSize;
      this.$refs.agGridComponent.loading = true;

      _Api
        .getMaterialBarcodeList(obj)
        .then(function (response) {
          var data = response.data;
          that.$refs.agGridComponent.loading = false;
          if (data.code == "1") {
            if (data.total > 0) {
              that.rowData = data.rows.splice(0);
              that.$refs.agGridComponent.gridOptions.api.setRowData(
                that.rowData
              );
              that.total = data.total;
            } else {
              that.$refs.agGridComponent.gridOptions.api.setRowData([]);
              that.total = 0;
              that.current = 1;
              that.currentPage = 1;
            }
          } else {
            that.$alert(data.info, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure",
            });
            that.$refs.agGridComponent.gridOptions.api.setRowData([]);
            that.total = 0;
            that.current = 1;
            that.currentPage = 1;
          }
        })
        .catch(() => {
          that.$alert("操作失败", {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
          that.$refs.agGridComponent.loading = false;
        });
    },
    add() {
      this.ruleForm = {
        isBarCode: "",
        matCode: "",
        matName: "",
      };
      this.dialogVisible = true;
      this.disState = true;
    },
    del() {
      var that = this;
      var row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
      if (row.length <= 0) {
        this.$alert("提示：请选择需要删除的数据", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      }
      this.$confirm("是否确认删除该数据？", "消息提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        distinguishCancelAndClose: true,
      })
        .then(() => {
          var id = "";
          for (var i = 0; i < row.length; i++) {
            id += row[i].id + ",";
          }
          id = id.substr(0, id.length - 1);
          var obj = {
            id: id,
            delFlag: 0,
            modifyer: this.$global.user.loginName,
            modifyerId: this.$global.user.id,
          };
          _Api
            .delMaterialBarcode(obj)
            .then(function (response) {
              var data = response.data;
              if (data.code == "1") {
                that.$message({
                  message: "操作成功",
                  type: "success",
                });
              } else {
                that.$alert(data.info, {
                  showClose: false,
                  confirmButton: "确定",
                  customClass: "alertFailure",
                });
              }
              that.search();
            })
            .catch((err) => {
              that.$alert(err.data.message, {
                showClose: false,
                confirmButton: "确定",
                customClass: "alertFailure",
              });
            });
        })
        .catch(() => {});
    },
    importInfo() {
      this.importDialogVisible = true;
    },
    handleSizeChange(params) {
      this.currentPage = 1;
      this.pageSize = params;
      this.search();
    },
    handleCurrentChange(params) {
      this.currentPage = params;
      this.search();
    },
    handlePrevClick(params) {
      //				if(this.matCode ||  this.matName)
      //					params = 1;
      //				this.current = params;
      this.currentPage = params;
      this.search();
    },
    handleNextClick(params) {
      //				if(this.matCode || this.matName)
      //					params = 1;
      //				this.current = params;
      this.currentPage = params;
      this.search();
    },
    handleClose(done) {
      this.$refs.ruleForm.resetFields();
      this.$refs.ruleForm.clearValidate();
      done();
    },
    cancel() {
      this.$refs.ruleForm.resetFields();
      this.$refs.ruleForm.clearValidate();
      this.dialogVisible = false;
    },
    saveData() {
      var that = this;
      if (this.ruleForm.isBarCode == true) {
        this.ruleForm.isBarCode = 1;
      } else {
        this.ruleForm.isBarCode = 0;
      }
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          that.ruleForm.creator = this.$global.user.loginName;
          that.ruleForm.creatorId = this.$global.user.id;
          this.disState = true;
          _Api
            .saveMaterialBarcode(that.ruleForm)
            .then(function (response) {
              var data = response.data;
              if (data.code == "1") {
                that.$message({
                  message: "保存成功",
                  type: "success",
                });
                that.ruleForm = {};
                that.dialogVisible = false;
                that.search();
              } else {
                that.$alert(data.info, {
                  showClose: false,
                  confirmButton: "确定",
                  customClass: "alertFailure",
                });
              }
              that.disState = false;
            })
            .catch((err) => {
              that.$alert(err.data.message, {
                showClose: false,
                confirmButton: "确定",
                customClass: "alertFailure",
              });
              that.disState = false;
            });
        } else {
          return false;
        }
      });
    },
    saveDataAgain() {
      var that = this;
      if (this.ruleForm.isBarCode == true) {
        this.ruleForm.isBarCode = 1;
      } else {
        this.ruleForm.isBarCode = 0;
      }
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          that.ruleForm.creator = this.$global.user.loginName;
          that.ruleForm.creatorId = this.$global.user.id;
          this.disState = true;
          _Api
            .saveMaterialBarcode(that.ruleForm)
            .then(function (response) {
              var data = response.data;
              if (data.code == "1") {
                that.$message({
                  message: "保存成功",
                  type: "success",
                });
                that.ruleForm = {};
                that.ruleForm.isBarCode = false;
                that.search();
              } else {
                that.$alert(data.info, {
                  showClose: false,
                  confirmButton: "确定",
                  customClass: "alertFailure",
                });
              }
              that.disState = false;
            })
            .catch((err) => {
              that.$alert(err.data.message, {
                showClose: false,
                confirmButton: "确定",
                customClass: "alertFailure",
              });
              that.disState = false;
            });
        } else {
          return false;
        }
      });
    },
    check() {
      this.ruleForm.matCode = this.ruleForm.matCode.replace(/[^\.\d]/g, "");
      if (/\d/.test(this.ruleForm.matCode)) this.disState = false;
      else this.disState = true;
    },
    matCodeBlur() {
      var that = this;
      if (this.ruleForm.matCode) {
        if (this.ruleForm.matCode.toString().length >= 10) {
          this.inputDis = true;
          var obj = {
            matCode: this.ruleForm.matCode,
          };
          _Api
            .getMatName(obj)
            .then(function (response) {
              that.inputDis = false;
              var data = response.data;
              if (data.code == "1") {
                // that.ruleForm.matName = data.rows;
                that.$set(that.ruleForm, "matName", data.rows);
                that.$refs.ruleForm.clearValidate();
              } else {
                that.$alert(data.info, {
                  showClose: false,
                  confirmButton: "确定",
                  customClass: "alertFailure",
                });
              }
            })
            .catch(() => {
              that.inputDis = false;
              that.$alert("操作失败", {
                showClose: false,
                confirmButton: "确定",
                customClass: "alertFailure",
              });
            });
        }
      }
    },
    // 获取合同导入模板
    getContractTemp() {
      fileStream.getPrintTempUrl("materialImport").then((url) => {
        this.tempUrl = url;
      });
    },
  },
  components: {
    agGridComponents,
    importFile,
  },
  mounted() {
    this.getContractTemp();
    this.search();
  },
};
</script>
